﻿using SqlSugar;
using MyBlog.WebApi.Data;
using MyBlog.WebApi.Repositories.Interfaces;
using MyBlog.WebApi.Repositories.Implementations;
using MyBlog.WebApi.Services.Interfaces;
using MyBlog.WebApi.Services.Implementations;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace MyBlog.WebApi
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // 添加 MVC 和 API 服务
            builder.Services.AddControllers(); // 添加 API 支持
            builder.Services.AddControllersWithViews(); // 保留 MVC 支持

            // 配置 SqlSugar
            builder.Services.AddSingleton<ISqlSugarClient>(provider =>
            {
                var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
                return new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = connectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                },
                db =>
                {
                    // 开发环境下打印 SQL 语句
                    if (builder.Environment.IsDevelopment())
                    {
                        db.Aop.OnLogExecuting = (sql, pars) =>
                        {
                            Console.WriteLine($"SQL: {sql}");
                            if (pars != null && pars.Any())
                            {
                                Console.WriteLine($"Parameters: {string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"))}");
                            }
                        };
                    }
                });
            });

            // 注册数据库上下文
            builder.Services.AddScoped<BlogDbContext>();

            // 注册仓储
            builder.Services.AddScoped<IBlogPostRepository, BlogPostRepository>();
            builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();

            // 注册服务
            builder.Services.AddScoped<IBlogPostService, BlogPostService>();
            builder.Services.AddScoped<ICategoryService, CategoryService>();

            var app = builder.Build();

            // 初始化数据库
            using (var scope = app.Services.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService<BlogDbContext>();
                await dbContext.InitializeDatabaseAsync();
            }

            // 配置 HTTP 请求管道
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");// 🔧 异常处理中间件
                app.UseHsts();// 🔧 HSTS 中间件
            }

            app.UseHttpsRedirection();// 🔧 HTTPS 重定向中间件
            app.UseStaticFiles();// 🔧 静态文件服务中间件

            app.UseRouting(); // 🔧 路由中间件

            app.UseAuthorization();// 🔧 授权中间件
            app.UseMiddleware<RequestLocalizationMiddleware>();// 🔧 本地化中间件
            app.UseMiddleware<PerformanceMiddleware>(); // 注册性能监测中间件

            // 配置路由
            app.MapControllers(); // 添加 API 路由
            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            // 配置博客相关路由
            app.MapControllerRoute(
                name: "blog",
                pattern: "blog/{action=Index}/{id?}",
                defaults: new { controller = "Blog" });

            app.MapControllerRoute(
                name: "admin",
                pattern: "admin/{action=Posts}",
                defaults: new { controller = "Admin" });

            app.Run();
        }
    }
    //自定义中间件
    public class PerformanceMiddleware// 🔧 性能监测中间件
    {
        private readonly RequestDelegate _next;// 🔧 下一个中间件委托
        private readonly ILogger<PerformanceMiddleware> _logger;// 🔧 日志记录器

        public PerformanceMiddleware(RequestDelegate next, ILogger<PerformanceMiddleware> logger)// 🔧 构造函数
        {
            _next = next;// 🔧 初始化下一个中间件委托
            _logger = logger;// 🔧 初始化日志记录器
        }

        public async Task InvokeAsync(HttpContext context)// 🔧 异步调用方法
        {
            var stopwatch = Stopwatch.StartNew();// 🔧 启动计时器

            await _next(context);// 🔧 调用下一个中间件

            stopwatch.Stop();// 🔧 停止计时器

            if (stopwatch.ElapsedMilliseconds > 1000) // 超过1秒的请求
            {
                _logger.LogWarning("Slow request: {Method} {Url} took {ElapsedMilliseconds}ms",
                    context.Request.Method, context.Request.Path, stopwatch.ElapsedMilliseconds);// 🔧 记录慢请求日志
            }
        }
    }
}
